package com.jms.product.web;

import com.alibaba.fastjson.JSON;
import com.jms.common.exception.BizCodeEnum;
import com.jms.common.utils.HttpUtils;
import com.jms.common.utils.R;
import com.jms.product.constant.AuthServerConstant;
import com.jms.product.entity.UserBaseEntity;
import com.jms.product.service.LoginService;
import com.jms.product.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jamison
 * @version 1.0
 * @date 2021/6/13 22:51
 */
@Slf4j
@RestController
public class Oauth2Controller {

    @Autowired
    private LoginService loginService;

    @PostMapping("/oauth2.0/weibo/success")
    public R weibo(@RequestParam("code") String code,
                   HttpSession httpSession,
                   HttpServletResponse servletResponse) throws Exception {
        // 1.根据code获取access-token
        Map<String, String> query = new HashMap<>();
        query.put("client_id", "839991271");
        query.put("client_secret", "5eedc465dd3301c221c4d6997f20580e");
        query.put("grant_type", "authorization_code");
        query.put("redirect_uri", "http://www.childrenwear.com:8000/oauth");
        query.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                new HashMap<String, String>(),
                new HashMap<String, String>(), query);
        // 2.处理结果
        if (response.getStatusLine().getStatusCode() == 200) {
            String s = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(s, SocialUser.class);
            // log.info("socialUser=====>" + socialUser.toString());
            // 根据获取的token等信息去登录（没有注册过就先注册再返回用户信息，注册过就直接查询用户信息并返回）
            UserBaseEntity userBaseEntity = loginService.oauth2Login(socialUser);
            // log.info("userBaseEntity:-------------->{}", userBaseEntity);
            if (userBaseEntity != null){
                // 登录成功
                httpSession.setAttribute(AuthServerConstant.LOGIN_USER, userBaseEntity);
                httpSession.setMaxInactiveInterval(60 * 60);
                //存sessionId的cookie
                Cookie cookieSId = new Cookie("JSESSIONID",httpSession.getId());
                cookieSId.setMaxAge(60 * 60);
                cookieSId.setPath("/");
                cookieSId.setDomain("www.childrenwear.com");
                servletResponse.addCookie(cookieSId);
                return R.ok().setData(BizCodeEnum.LOGIN_SUCCESS.getMsg());
            }
        }
        return R.error(BizCodeEnum.WEIBO_LOGIN_FAIL.getCode(), BizCodeEnum.WEIBO_LOGIN_FAIL.getMsg());
    }
}
